package com.qf.ceshi0616.category.controller;

import com.qf.ceshi0616.category.entity.Category;
import com.qf.ceshi0616.category.entity.CategoryVO;
import com.qf.ceshi0616.category.service.ICategoryService;
import com.qf.ceshi0616.category.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 商品分类 前端控制器
 * </p>
 *
 * @author uniq7xi
 * @since 2023-06-16
 */
@RestController
@RequestMapping("/index")
public class CategoryController {
    @Autowired
    ICategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    private static final String CATEGORY = "category";

    @GetMapping("/category-list")
    public ResultVo categoryAll(){
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //redisTemplate.delete(CATEGORY);
        boolean hasKey = redisTemplate.hasKey(CATEGORY);
        if (hasKey) { // 如果Redis中已经有缓存数据，则直接返回缓存数据
            List<CategoryVO> categoryVOList = (List<CategoryVO>) valueOperations.get(CATEGORY);
            return ResultVo.ok(categoryVOList);
        } else { // 如果Redis中没有缓存数据，则查询数据库并加入缓存
            List<CategoryVO> categoryVOList = categoryService.getAllCategories();
            valueOperations.set(CATEGORY, categoryVOList);
            return ResultVo.ok(categoryVOList);
        }
    }

}
